package com.shinechain.botModel;

import com.shinechain.dao.RewardMapper;
import com.shinechain.dao.RewardUserMapper;
import com.shinechain.model.Reward;
import com.shinechain.model.RewardUser;
import com.shinechain.utils.RedPacketUtil;
import com.shinechain.utils.RewardUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException;

import java.text.SimpleDateFormat;
import java.util.*;

public class ShineChainBot extends TelegramLongPollingBot {

    public static RewardMapper rewardMapper;
    public static RewardUserMapper rewardUserMapper;
    public static String bitName = "共识token";


    @Override
    public void onUpdateReceived(Update update) {
       // if(update.hasMessage() && update.getMessage().hasText()){
        //}

        if (update.hasMessage() && update.getMessage().isCommand()) {
            String[] texts = update.getMessage().getText().split(" ");
            String username = "";
            username = update.getMessage().getFrom().getFirstName() + " " + update.getMessage().getFrom().getLastName();
            username = username.replace("null","");
            if (texts[0].equals("/key")) {
                //验证口令是否存在
                if (RewardUtil.hashMap.containsKey(texts[1])) {
                    Reward myReward = RewardUtil.hashMap.get(texts[1]);
                    //检查对应token的红包是否领取完毕
                    if (RewardUtil.userMap.get(texts[1]).size() < myReward.getAmount()) {

                        //检查对应token的红包中是否已被该用户领取
                        if (!RewardUtil.userMap.get(texts[1]).containsKey(update.getMessage().getFrom().getId())) {
                            //分发钱包
                            HashMap list = RewardUtil.userMap.get(texts[1]);
                            RewardUser rewardUser = new RewardUser();
                            Date dNow = new Date();
                            rewardUser.setGetTime(dNow);
                            //rewardUser.setId(0);
                            rewardUser.setUsername(username);
                            rewardUser.setUserid(update.getMessage().getFrom().getId() + "");
                            rewardUser.setToken(texts[1]);
                            int times = RewardUtil.timesMap.get(texts[1]);
                            rewardUser.setReward(RewardUtil.redPacketMap.get(texts[1]).get(times));

                            //存入数据库
                            rewardUserMapper.insert(rewardUser);
                            RewardUtil.timesMap.put(texts[1], times + 1);
                            list.put(update.getMessage().getFrom().getId(), rewardUser);
                            RewardUtil.userMap.put(texts[1], list);
                            String text = "@" + username + " ,恭喜您,获得" + rewardUser.getReward() + bitName
                                    + ",还剩"+(myReward.getAmount()-RewardUtil.userMap.get(texts[1]).size())+"份红包";
                            this.sendMessage(update.getMessage().getChatId(), text);
                            //最后一个人领完红包就报出红包情况
                            if (RewardUtil.userMap.get(texts[1]).size() == myReward.getAmount()) {
                                this.sendRewardUsers(texts[1], update.getMessage().getChatId());
                            }
                        } else {
                            this.sendMessage(update.getMessage().getChatId(), "@" + username +
                                    " ,您已领取了此红包,已获得" +
                                    RewardUtil.userMap.get(texts[1]).get(update.getMessage().getFrom().getId()).getReward() +bitName+
                                    ",请留意下次红包,输入/mine 查看共获得多少红包"
                            );
                        }
                    } else {
                        this.sendMessage(update.getMessage().getChatId(), "@" + username +
                                "此红包已领取完,请留意下次红包");
                    }

                } else {
                    String text = "@" + username + " 您好,口令有误或红包已拿完,输入/mine 查看共获得多少红包";
                    this.sendMessage(update.getMessage().getChatId(), text);
                }
            } else if (texts[0].equals("/admin")) {
                //管理机器人发红包，输入密码、输入口令、多少份、多少数量的币、用空格间隔
                if (texts[1].equals("shinechain")) {
                    if (!RewardUtil.hashMap.containsKey(texts[2])) {
                        Date dNow = new Date();
                        Reward reward = new Reward();
                        reward.setGetTime(dNow);
                        reward.setToken(texts[2]);
                        reward.setAmount(Integer.parseInt(texts[3]));
                        reward.setRewardtotal(Double.parseDouble(texts[4]));
                        System.out.println(reward.toString());

                        //存入数据库
                        rewardMapper.insert(reward);
                        //加入Reward到hashma中
                        RewardUtil.hashMap.put(texts[2], reward);
                        //初始化用户列表
                        HashMap<String, RewardUser> list = new HashMap<>();
                        //加入到usermap
                        RewardUtil.userMap.put(reward.getToken(), list);
                        //初始化次数
                        RewardUtil.timesMap.put(texts[2], 0);
                        //生成随机钱包
                        RewardUtil.redPacketMap.put(reward.getToken(), RedPacketUtil.getList(reward.getRewardtotal(), reward.getAmount()));
                        this.sendMessage(-1001389649632L, "红包来拉！有" + reward.getAmount() + "份，共" + reward.getRewardtotal() + bitName+". \n 输入口令领取：/key " + reward.getToken());
                    } else {
                        this.sendMessage(update.getMessage().getChatId(), "口令为：" + texts[2] + "的红包未领取完，请使用其他口令");
                    }
                    //初始化Reward

                } else {
                    this.sendMessage(update.getMessage().getChatId(), "请输入正确密码");
                }
            } else if (texts[0].equals("/mine")) {
                this.sendMessage(update.getMessage().getChatId(), "@" + username + " ,您目前已拥有红包" + String.format("%.3f", this.getUserAllReward(update.getMessage().getFrom().getId())) + bitName);
            } else if (texts[0].equals("/start")) {
                this.sendMessage(update.getMessage().getChatId(), "输入: /admin 密码 口令 数量 金额，（以空格隔开）即可开启红包 \n " +
                        "输入: /mine 即可查询自己拥有的红包数量 \n" +
                        "输入: /bind 闪链糖果账号 ,即可绑定，领取糖果");
            } else if (texts[0].equals("/bind")) {
                this.sendMessage(update.getMessage().getChatId(), "。。。。绑定成功，。。已转入您的账户");
            }

        }
    }

    @Override
    public String getBotUsername() {
        return "ShineChainAuto_bot";
    }

    @Override
    public String getBotToken() {
        return "645393934:AAGQPTIvb6vf1V0zmBDgT_Ev5_JAoSsU9V8";
    }

    public ShineChainBot(DefaultBotOptions options) {
        super(options);
    }

    public void sendMessage(long chatId, String text) {
        SendMessage message = new SendMessage() // Create a SendMessage object with mandatory fields
                .setChatId(chatId)
                .setText(text);
        try {
            execute(message); // Call method to send the message
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }

    public void sendRewardUsers(String token, Long chatId) {
        String msg = "口令红包: " + token + "\n";
        Reward reward = RewardUtil.hashMap.get(token);
        msg += reward.getAmount() + "/" + RewardUtil.userMap.get(token).size() + "已领" + " O(∩_∩)O" + " \n";
        msg += "__ 时间 __  |  ____ 昵称 ____  |  __ 数额 __ \n";
        for (RewardUser rewardUser : RewardUtil.userMap.get(token).values()) {
            msg += "---------------------------------------------------- \n ";
            SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss");
            String mytime = ft.format(rewardUser.getGetTime());
            msg += mytime + " | " + rewardUser.getUsername() + " | " + rewardUser.getReward() + "\n";
        }
        this.sendMessage(chatId, msg);
    }

    public Double getUserAllReward(int userId) {
        List<Double> list = rewardUserMapper.findAllReward(userId + "");
        double allMoney = 0;
        for (Double money : list) {
            allMoney += money;
        }
        return allMoney;
    }
}
